﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace HelperFromTheSkeleton.JwtHelper;
public class JwtManage
{
    public JwtSecurityToken? Token { get; set; }

    private string? _tokenString;
    public string TokenString
    {
        get
        {
            GetScopedToken();
            return _tokenString ?? "";
        }
        set
        {
            _tokenString = value;
        }
    }

    private readonly TokenValidationParameters _parameters;
    private readonly int _expiresIn;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="issuerSigningKey">密钥</param>
    /// <param name="expires">有效时间，效时</param>
    public JwtManage(TokenValidationParameters parameters, int expires)
    {
        _expiresIn = expires;
        _parameters = parameters;
        _tokenString = "";
    }

    public string CreateToken(Dictionary<string, string> Claim)
    {
        var signingCredentials = new SigningCredentials(_parameters.IssuerSigningKey, SecurityAlgorithms.HmacSha256);
        var claims = Claim.Select(m => new Claim(m.Key, m.Value)).ToArray();
        var startTime = DateTime.Now;
        var endTime = startTime.AddHours(_expiresIn);
        JwtSecurityToken token = new("TrPlatform", "TrPlatform", claims, DateTime.Now, endTime, signingCredentials);
        var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
        return tokenString;
    }

    private void GetScopedToken()
    {
        if (Token == null) return;
        DateTime nowTime = DateTime.Now;
        var tokenEndTime = Token.ValidTo;
        if (DateTime.Compare(nowTime, tokenEndTime) >= 0)
        {
            _tokenString = CreateToken(Token.Claims.ToDictionary(m => m.ValueType, m => m.Value));
        }
    }
}
